package com.example.demo.Tools;

import com.example.demo.Tools.Message;
import com.example.demo.dao.ChatJpa;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@CrossOrigin(origins = "*", maxAge = 3600)
@ServerEndpoint("/chat/{username}")
public class ChatRoomServerEndpoint {
    /**
     * 存活的session集合（使用线程安全的map保存）
     */
    private static Map<String, Session> livingSessions = new ConcurrentHashMap<>();

    /**
     * 建立连接的回调方法
     *
     * @param session  与客户端的WebSocket连接会话
     */
    //将存活的session装入map列表中
    @OnOpen
    public void onOpen(Session session,@PathParam(value = "username") String username) {
//        System.out.println(session+"          "+username);
        System.out.println(username+"连接成功");
        livingSessions.put(username, session);
    }
    /**
     * 收到客户端消息的回调方法
     *
     * @param message 客户端传过来的消息
     */
    //服务器接收到消息,并进行私聊逻辑操作
    @OnMessage
    public void onMessage(String message,@PathParam(value = "username") String username) {
//        将message分解成我们想要的东西,私聊
        System.out.println("发送消息"+username);
        try{
            ObjectMapper mapper=new ObjectMapper();
            Message message1=mapper.readValue(message,Message.class);
            //调用函数
            if(message1.getSender().equals(message1.getToUser())){
                sendsoloMessage(message1.getSender(),message1.getToUser(),message);
                return;
            }
            sendMessage(message1.getSender(),message1.getToUser(),message);
//            System.out.print(message1.getMessage()+" "+message1.getSender()+" "+message1.getToUser());
        }catch(Exception e){
            System.out.println("报错"+e);
        }

    }
    /**
     * 发生错误的回调方法
     *
     * @param session
     * @param error
     */
    //出现bug
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }
    /**
     * 关闭连接的回调方法
     */
    //关闭链接,删除session,并且广播用户退出聊天
    @OnClose
    public void onClose(Session session,@PathParam(value = "username") String username) {
        System.out.println(session+"          "+username);
        livingSessions.remove(username);
    }


    /**
     * 单独发送消息
     *
     * @param message
     * @param message
     */
    //既然是私聊,就同时将数据发送给发送者和接收者
    public void sendMessage(String sender, String receiver,String message) {
        try {
//            session.getBasicRemote().sendText(message);
            livingSessions.get(sender).getBasicRemote().sendText(message);
            livingSessions.get(receiver).getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //存在自己给自己发送消息,则只发送给自己
    public void sendsoloMessage(String sender, String receiver,String message) {
        try {
//            session.getBasicRemote().sendText(message);
            livingSessions.get(sender).getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}